using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Soft2ApiDemo.Domain;
using Soft2ApiDemo.Domain.Repository;
using Soft2ApiDemo.Infrastructure.Db;

namespace Soft2ApiDemo.Infrastructure.Repository
{
    /// <summary>
    /// CRUD接口的一个实现
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class RepositoryBase<T> : IRepositoryBase<T> where T : BaseEntity
    {
        private readonly Soft2ApiDemoDbContext _db;

        private DbSet<T> _table;

        public RepositoryBase(Soft2ApiDemoDbContext db)
        {
            _db = db;
            _table = _db.Set<T>();
        }

        public T GetById(Guid id)
        {
            var entity = _table.Where(x => x.Id == id).FirstOrDefault();
            return entity;
        }

        public IQueryable<T> Table
        {
            get
            {
                if (_table == null)
                {
                    _table = _db.Set<T>();
                }
                return _table.AsNoTracking().AsQueryable<T>();
            }
        }

        public void Add(T entity)
        {
            entity.IsActived = true;
            entity.IsDeleted = false;
            entity.CreatedAt = DateTime.Now;
            entity.UpdatedAt = DateTime.Now;
            entity.DisplayOrder = 0;
            _db.Add (entity);
            _db.SaveChanges();
        }

        public void Update(T entity)
        {
            entity.UpdatedAt = DateTime.Now;
            _db.Update (entity);
            _db.SaveChanges();
        }

        public void Delete(Guid id)
        {
            var entity = GetById(id);
            if (entity != null)
            {
                entity.IsDeleted=true;
                this.Update(entity);
                _db.SaveChanges();
            }
        }
    }
}
